<?php
//set_time_limit(0);
$filename  = dirname(__FILE__)."/chat/";
if(@$_REQUEST["act"]=="user")
{
	changeMember();
}
// store new message in the file
$msg = isset($_REQUEST['msg']) ? $_REQUEST['msg'] : '';
if ($msg != '')
{
	file_put_contents($filename.$_REQUEST["cur_user"],$msg);
	die();
}
// infinite loop until the data file is not modified
$filename.="../admin";

$lastmodif    = isset($_REQUEST['timestamp']) ? $_REQUEST['timestamp'] : 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) // check if the data file has been modified
{
	usleep(10000); // sleep 10ms to unload the CPU
	clearstatcache();
	$currentmodif = filemtime($filename);
}

// return a json array
$response = array();
$response['msg']       = file_get_contents($filename);
lock_write($filename,"","w");
$response['timestamp'] = $currentmodif;

echo json_encode($response);
//echo "bb";
flush();


function lock_write($file,$contents,$mode="a+")
{
	$fp = fopen($file, $mode);

	if (flock($fp, LOCK_EX))
	{ // 进行排它型锁定
		fwrite($fp, $contents);
		flock($fp, LOCK_UN); // 释放锁定
	}
	else
	{
		//echo "Couldn't lock the file !";
	}

	fclose($fp);
}
function changeMember()
{
	$response["remove_user"]=array();
	$response["add_user"]="";
	
	while (empty($response["remove_user"])&&empty($response["add_user"]))
	{
		usleep(10000);
		clearstatcache();
		$members=scandir(dirname(__FILE__)."/chat/");
		array_shift($members);
		array_shift($members);
		if(!empty($members))
		{
			foreach ($members as $member)
			{
				if(time()-fileatime(dirname(__FILE__)."/chat/$member")>10)
				{
					$response["remove_user"][]=$member;
					unlink(dirname(__FILE__)."/chat/$member");
				}
			}
		}	
		$response["remove_user"]=@implode(",",$response["remove_user"]);
		$response["add_user"]=file_get_contents(dirname(__FILE__)."/new_member");
		if(empty($response["remove_user"]))
		{
			$response["remove_user"]="";
		}
		lock_write(dirname(__FILE__)."/new_member","","w");
		
	}
	echo json_encode($response);
	//echo "bb";
	flush();
	exit();
}
?>